package com.example.wm.controller;

import cn.hutool.http.Header;
import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpResponse;
import cn.hutool.http.HttpStatus;
import cn.hutool.json.JSONUtil;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.example.wm.common.Result;
import com.example.wm.common.ResultData;
import com.example.wm.entity.*;
import com.example.wm.service.EmployedManageService;
import com.example.wm.service.MaterialLibraryService;
import com.example.wm.service.ProductunpackingService;
import com.example.wm.service.TenderDetailService;
import com.example.wm.utils.TsyUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.http.HttpEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.util.EntityUtils;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.io.IOException;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.util.*;
import java.util.stream.Collectors;

@Slf4j
@RestController
@RequestMapping("/Productunpacking")
public class ProductunpackingContorller {
    @Resource
    private EmployedManageService employedManageService;
    @Resource
    private ProductunpackingService productunpackingService;
    @Resource
    private TsyUtils tsyUtils;
    @Resource
    private TenderDetailService tenderDetailService;
    @Resource
    private MaterialLibraryService materialLibraryService;
    @Transactional
    @PostMapping("/save")
    public Result save(@RequestBody Productunpacking productunpacking) {
        // 检查材料库中是否已存在该材料
        boolean exists = materialLibraryService.list()
                .stream()
                .anyMatch(lib -> lib.getMatername().equals(productunpacking.getNametd()));

        // 如果不存在，自动添加
        if (!exists) {
            MaterialLibrary newMaterial = new MaterialLibrary();
            newMaterial.setMatername(productunpacking.getNametd());
           newMaterial.setInserttime(tsyUtils.getnowtime());
           newMaterial.setMarheavy(productunpacking.getHeavey());
           newMaterial.setImglist(productunpacking.getImglist());
            newMaterial.setCurrentprice(productunpacking.getCurrentprice());
            newMaterial.setUnit(productunpacking.getUnit());


            materialLibraryService.save(newMaterial);
        }

        // 保存产品拆解记录
        productunpacking.setInserttime(tsyUtils.getnowtime());
        Boolean b = productunpackingService.save(productunpacking);

        return ResultData.success(b);
    }
    @PostMapping("/findmater")
    public Result findmater(@RequestBody Productunpacking productunpacking) {
        LambdaQueryWrapper<Productunpacking> lq=new LambdaQueryWrapper<>();
        lq.eq(Productunpacking::getTenderdetailid,productunpacking.getTenderdetailid());
        List<Productunpacking> list=   productunpackingService.list(lq);
        return ResultData.success(list);
    }
    @Transactional
    @PostMapping("/delete")
    public Result delete(@RequestBody Productunpacking productunpacking) {
        LambdaQueryWrapper<Productunpacking> lq=new LambdaQueryWrapper<>();
        lq.eq(Productunpacking::getId,productunpacking.getId());

      Boolean b=   productunpackingService.remove(lq);
        return ResultData.success(b);
    }
    @Transactional
    @PostMapping("/update")
    public Result update(@RequestBody Productunpacking productunpacking) {
        Boolean b=   productunpackingService.updateById(productunpacking);
        return ResultData.success(b);
    }
//所有的出入或库库存信息
@PostMapping("/findInventroy")
public Result findInventroy(@RequestBody JSONObject jsonObject) {
    LambdaQueryWrapper<Productunpacking> lambdaQueryWrapper = new LambdaQueryWrapper<>();
    lambdaQueryWrapper.eq(Productunpacking::getTypeventroy, jsonObject.getString("typeventroy"));
    if(Objects.equals(jsonObject.getString("inserttime"), "1")){
        LocalDate today = LocalDate.now();
        LocalDateTime startOfDay = today.atStartOfDay(); // 00:00:00
        LocalDateTime endOfDay = today.atTime(23, 59, 59); // 23:59:59
        lambdaQueryWrapper.between(Productunpacking::getInserttime, startOfDay, endOfDay);
    }
    // 先查询所有数据（不分页），因为需要分组处理
    List<Productunpacking> allRecords = productunpackingService.list(lambdaQueryWrapper);

    // 按 nametd 分组并累加 heavey 和 number
    Map<String, Productunpacking> groupedMap = new HashMap<>();

    for (Productunpacking item : allRecords) {
        String nametd = item.getNametd();

        if (groupedMap.containsKey(nametd)) {
            Productunpacking existing = groupedMap.get(nametd);

            // 处理 heavey 字段，去除 "kg" 后缀后相加
            BigDecimal existingHeavey = parseHeavey(existing.getHeavey());
            BigDecimal currentHeavey = parseHeavey(item.getHeavey());
            BigDecimal sumHeavey = existingHeavey.add(currentHeavey);

            // 设置累加后的值，保留两位小数并添加 "kg" 后缀
            String formattedHeavey = String.valueOf(sumHeavey.setScale(2, RoundingMode.HALF_UP));
            existing.setHeavey(formattedHeavey);

            // 处理 number 字段，转换为数值后相加
            BigDecimal existingNumber = parseNumber(existing.getNumber());
            BigDecimal currentNumber = parseNumber(item.getNumber());
            BigDecimal sumNumber = existingNumber.add(currentNumber);

            // 设置累加后的值，转换为字符串
            existing.setNumber(sumNumber.toString());
        } else {
            // 如果不存在，直接添加
            groupedMap.put(nametd, item);
        }
    }

    // 转换为列表
    List<Productunpacking> groupedList = new ArrayList<>(groupedMap.values());

    // 获取分页参数
    long currentPage = jsonObject.getLong("page");
    long pageSize = jsonObject.getLong("pageSize");

    // 计算总记录数和总页码
    long totalRecords = groupedList.size();
    long totalPages = (totalRecords + pageSize - 1) / pageSize;

    // 手动分页处理
    int startIndex = (int) ((currentPage - 1) * pageSize);
    int endIndex = Math.min(startIndex + (int) pageSize, groupedList.size());

    List<Productunpacking> pageRecords;
    if (startIndex < groupedList.size()) {
        pageRecords = groupedList.subList(startIndex, endIndex);
    } else {
        pageRecords = new ArrayList<>();
    }

    // 创建分页对象
    Page<Productunpacking> resultPage = new Page<>();
    resultPage.setRecords(pageRecords);
    resultPage.setTotal(totalRecords);
    resultPage.setCurrent(currentPage);
    resultPage.setSize(pageSize);
    resultPage.setPages(totalPages);

    return ResultData.success(resultPage);
}

    //出库入库总重量
    @PostMapping("/findall")
    public Result findall(@RequestBody Productunpacking productunpacking) {
        LambdaQueryWrapper<Productunpacking> lq = new LambdaQueryWrapper<>();
        lq.eq(Productunpacking::getTypeventroy, productunpacking.getTypeventroy());
        if(Objects.equals(productunpacking.getInserttime(), "1")){
            LocalDate today = LocalDate.now();
            LocalDateTime startOfDay = today.atStartOfDay(); // 00:00:00
            LocalDateTime endOfDay = today.atTime(23, 59, 59); // 23:59:59
            lq.between(Productunpacking::getInserttime, startOfDay, endOfDay);
        }
        List<Productunpacking> productunpackingList = productunpackingService.list(lq);

        Map<String, String> groupedMap = new HashMap<>();
        BigDecimal heavyall = BigDecimal.ZERO;  // 使用 BigDecimal 处理精度
        BigDecimal Moneyall = BigDecimal.ZERO;
        BigDecimal numberall = BigDecimal.ZERO; // 新增：统计总数量

        for (Productunpacking item : productunpackingList) {
            try {
                // 安全地解析各个字段，处理空值和空字符串
                BigDecimal heavey = parseHeavey(item.getHeavey());
                BigDecimal moneys = parseMoney(item.getMoneys());
                BigDecimal number = parseNumber(item.getNumber());

                // 累加重量
                heavyall = heavyall.add(heavey);

                // 累加数量
                numberall = numberall.add(number);

                // 累加金额（单价 × 重量）
                if (moneys != null && heavey != null) {
                    Moneyall = Moneyall.add(moneys.multiply(heavey));
                }
            } catch (Exception e) {
                // 记录日志或跳过有问题的数据
                continue;
            }
        }

        // 保留两位小数并转换为字符串
        String heavyallFormatted = String.valueOf(heavyall.setScale(2, RoundingMode.HALF_UP));
        String MoneyallFormatted = Moneyall.setScale(2, RoundingMode.HALF_UP).toString();
        String numberallFormatted = numberall.toString();

        groupedMap.put("heavyall", heavyallFormatted);
        groupedMap.put("Moneyall", MoneyallFormatted);
        groupedMap.put("numberall", numberallFormatted); // 新增：返回总数量

        return ResultData.success(groupedMap);
    }

    /**
     * 解析 heavey 字段，去除 "kg" 后缀并转换为 BigDecimal 数值
     */
    private BigDecimal parseHeavey(String heavey) {
        if (heavey == null || heavey.trim().isEmpty()) {
            return BigDecimal.ZERO;
        }

        try {
            // 去除各种大小写组合的 "kg" 后缀
            String cleanHeavey = heavey.trim().replaceAll("(?i)kg$", "");
            return new BigDecimal(cleanHeavey);
        } catch (NumberFormatException e) {
            return BigDecimal.ZERO;
        }
    }

    /**
     * 解析 moneys 字段并转换为 BigDecimal 数值
     */
    private BigDecimal parseMoney(String moneys) {
        if (moneys == null || moneys.trim().isEmpty()) {
            return BigDecimal.ZERO;
        }

        try {
            return new BigDecimal(moneys.trim());
        } catch (NumberFormatException e) {
            return BigDecimal.ZERO;
        }
    }

    /**
     * 解析 number 字段并转换为 BigDecimal 数值
     */
    private BigDecimal parseNumber(String number) {
        if (number == null || number.trim().isEmpty()) {
            return BigDecimal.ZERO;
        }

        try {
            return new BigDecimal(number.trim());
        } catch (NumberFormatException e) {
            return BigDecimal.ZERO;
        }
    }
//今日个人拆解数据
    @PostMapping("/todydata")
    public Result todydata(@RequestBody Productunpacking productunpacking) {
        LambdaQueryWrapper<Productunpacking> lq = new LambdaQueryWrapper<>();
        lq.eq(Productunpacking::getAddname, productunpacking.getAddname());
        // 添加今天的时间范围查询
        LocalDate today = LocalDate.now();
        LocalDateTime startOfDay = today.atStartOfDay(); // 00:00:00
        LocalDateTime endOfDay = today.atTime(23, 59, 59); // 23:59:59
        lq.between(Productunpacking::getInserttime, startOfDay, endOfDay);
        List<Productunpacking> list = productunpackingService.list(lq);

        // 获取所有不重复的 tenderdetailid
        Set<Integer> tenderDetailIds = list.stream()
                .map(Productunpacking::getTenderdetailid)
                .collect(Collectors.toSet());

        // 构建返回结果
        List<Map<String, Object>> resultList = tenderDetailIds.stream()
                .map(tenderDetailId -> {
                    // 获取 TenderDetails
                    LambdaQueryWrapper<TenderDetails> lambdaQueryWrapper = new LambdaQueryWrapper<>();
                    lambdaQueryWrapper.eq(TenderDetails::getId, tenderDetailId);
                    TenderDetails tenderDetails = tenderDetailService.getOne(lambdaQueryWrapper);

                    // 获取对应的 Productunpacking 列表
                    List<Productunpacking> tenderItems = list.stream()
                            .filter(item -> Objects.equals(item.getTenderdetailid(), tenderDetailId))
                            .collect(Collectors.toList());

                    // 构建返回结构
                    Map<String, Object> resultMap = new HashMap<>();
                    resultMap.put("tenderDetails", tenderDetails);
                    resultMap.put("tenderlist", tenderItems);

                    return resultMap;
                })
                .collect(Collectors.toList());

        return ResultData.success(resultList);
    }
//查询指定产品所有的入库或者出库信息

    @PostMapping("/findnameallbytype")
    public Result findnameallbytype(@RequestBody JSONObject jsonObject) {
        LambdaQueryWrapper<Productunpacking> lq=new LambdaQueryWrapper<>();
        lq.eq(Productunpacking::getNametd,jsonObject.getString("nametd"));
        lq.eq(Productunpacking::getTypeventroy,jsonObject.getString("type"));
        lq.orderByDesc(Productunpacking::getInserttime);
        Page<Productunpacking> pageInfo = new Page<>(jsonObject.getLong("page"), jsonObject.getLong("pageSize"));
        Page<Productunpacking> list = productunpackingService.page(pageInfo, lq);

        return ResultData.success(list);
    }

}
